package com.example.app.service.impl;

import com.example.app.constants.StateConstants;
import com.example.app.dao.mongdb.MongoUserRepository;
import com.example.app.model.Organ;
import com.example.app.model.Patient;
import com.example.app.model.User;
import com.example.app.service.UserService;
import org.apache.log4j.Logger;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wangtao on 2018/2/3.
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    private SQLManager sqlManager;

    @Autowired
    private MongoUserRepository mongoUserRepository;

    @Autowired
    private UserService userService;

    @Override
    public User findOneFromCache(Long id) {
        return mongoUserRepository.findOne(id);
    }

    @Override
    public List<User> findHealthcareFromCache(Long accountId, Long organId) {
        List<Integer> jobs = new ArrayList<>();
        jobs.add(StateConstants.USER_JOB_DOCTOR);
        jobs.add(StateConstants.USER_JOB_NURSE);
        return mongoUserRepository.findByAccountIdAndOrganIdAndJobInAndDeleteFlag(accountId, organId, jobs, 0);
    }

    @Override
    public List<User> findAllByJob(Long accountId, Long organId, int job) {
        return mongoUserRepository.findByAccountIdAndOrganIdAndJobAndDeleteFlag(accountId, organId, job, 0);
    }

    @Override
    public List<User> findAppointmentByJob(Patient patient, Organ organ, String datetime, int job) {
        List<User> resultList = new ArrayList<>();
        // 根据工种查询
        String idsStr = "";
        List<User> users = userService.findAllByJob(organ.getAccountId(), organ.getId(), job);
        for (User user : users) {
            idsStr += user.getId() + ",";
        }
        idsStr = idsStr.substring(0, idsStr.lastIndexOf(","));
        // 查询当天休息的
        StringBuilder sql = new StringBuilder("select user_id as userId from attendance_record");
        sql.append(" where user_id in(" + idsStr + ")");
        sql.append(" and record_type = " + StateConstants.ATTENDANCE_RECORD_TYPE_LEAVE);
        sql.append(" and status = " + StateConstants.ATTENDANCE_STATUS_AGREE);
        sql.append(" and start_time <= '" + datetime + "'");
        sql.append(" and end_time >= '" + datetime + "'");
        List<Long> ids = new ArrayList<>();
        List<Map> mapList = sqlManager.execute(new SQLReady(sql.toString()), Map.class);
        for (Map map : mapList) {
            ids.add(Long.valueOf(map.get("userId").toString()));
        }
        // 过滤掉不符合条件的
        for (User user : users) {
            if (!ids.contains(user.getId())) {
                resultList.add(user);
            }
        }
        return resultList;
    }
}
